#define _CRT_SECURE_NO_WARNINGS 1
#include"SeqList.h"

void InitSeqList(SL* ps)
{
	assert(ps != NULL);
	ps->data = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void CheckSeqList(SL* ps)
{
	SeqListType* tmp = NULL;
	int newcapacity = 0;
	assert(ps != NULL);
	if(ps->size == ps->capacity)
	{
		newcapacity = ps->capacity ==  0 ? 4 : ps->capacity * 2;
		tmp = (SeqListType*)realloc(ps->data,newcapacity * sizeof(SeqListType));
		if(tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->data = tmp;
		ps->capacity = newcapacity;
	}
}

void DestroySeqList(SL* ps)
{
	assert(ps != NULL);
	if(ps->data != NULL)
	{
		free(ps->data);
		ps->data = NULL;
		ps->size = 0;
		ps->capacity = 0;
	}
}

void SLPushBack(SL* ps,SeqListType x)
{
	SLInsert(ps,ps->size,x);
}

void SLPopBack(SL* ps)
{
	SLErase(ps,ps->size - 1);
}

void SLPushFront(SL* ps,SeqListType x)
{
	SLInsert(ps,0,x);
}

void SLPopFront(SL* ps)
{
	SLErase(ps,0);
}

void SLInsert(SL* ps,int pos,SeqListType x)
{
	int end = ps->size - 1;
	assert(ps != NULL);
	assert(ps >= 0);
	assert(pos <= ps->size);
	CheckSeqList(ps);
	while(pos <= end)
	{
		ps->data[end + 1] = ps->data[end];
		end--;
	}
	ps->data[pos] = x;
	ps->size++;
}

void SLErase(SL* ps,int pos)
{
	int begin = pos + 1;
	assert(ps != NULL);
	assert(pos >= 0);
	assert(pos < ps->size);
	while(begin < ps->size)
	{
		ps->data[begin - 1] = ps->data[begin];
		begin++;
	}
	ps->size--;
}

int Find(SL* ps,int TargetNumber,int begin)
{
	int i = begin;
	assert(ps != NULL);
	while(i < ps->size)
	{
		if(ps->data[i] == TargetNumber)
		{
			return i;
		}
		i++;
	}
	return -1;
}

void PrintSeqList(SL* ps)
{
	int i = 0;
	for(i = 0; i < ps->size; i++)
	{
		printf("%d ",ps->data[i]);
	}
	printf("\n");
}